package com.smartcruise.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.provider.Settings;
import android.view.WindowManager;

import com.smartcruise.MyApplication;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by codbking on 2016/12/10.
 */
public class Utils {

    public static int getColor(Context context, int res) {
        Resources r = context.getResources();
        return r.getColor(res);
    }

    public static float getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }


    public static int px(float dipValue) {
        Resources r = Resources.getSystem();
        final float scale = r.getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    //获取显示版本
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    //获取版本信息
    public static int getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static StateListDrawable getRoundSelectorDrawable(int alpha, int color, int radir) {
        Drawable pressDrawable = getRoundDrawalbe(alpha, color, radir);
        Drawable normalDrawable = getRoundDrawalbe(color, radir);
        return getStateListDrawable(pressDrawable, normalDrawable);
    }

    //获取带透明度的圆角矩形
    public static Drawable getRoundDrawalbe(int alpha, int color, int radir) {
        int normalColor = Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
        Drawable normalDrawable = getRoundDrawalbe(normalColor, radir);
        return normalDrawable;
    }


    //根据颜色获取圆角矩形
    public static Drawable getRoundDrawalbe(int color, int radir) {
        radir = px(radir);
        GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{color, color});
        drawable.setCornerRadius(radir);
        return drawable;
    }

    public static StateListDrawable getStateListDrawable(Drawable pressDrawable, Drawable normalDrawable) {
        int pressed = android.R.attr.state_pressed;
        int select = android.R.attr.state_selected;
        StateListDrawable drawable = new StateListDrawable();
        drawable.addState(new int[]{pressed}, pressDrawable);
        drawable.addState(new int[]{select}, pressDrawable);
        drawable.addState(new int[]{}, normalDrawable);
        return drawable;
    }

    public static StateListDrawable getSelectDrawable(int color) {
        int select = android.R.attr.state_selected;
        StateListDrawable drawable = new StateListDrawable();

        GradientDrawable drawable2 = new GradientDrawable();
        drawable2.setShape(GradientDrawable.OVAL);
        drawable2.setColor(color);

        drawable.addState(new int[]{select}, drawable2);
        drawable.addState(new int[]{}, null);

        return drawable;
    }

    public static final String baiduMap = "com.baidu.BaiduMap";
    public static final String gaodeMap = "com.autonavi.minimap";
    public static final String tencentMap = "com.tencent.map";

    public static boolean isAvailable(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    public static boolean isBaiduMapAvailable(Context context) {
        return isAvailable(context, baiduMap);
    }

    public static boolean isGaodeMapAvailable(Context context) {
        return isAvailable(context, gaodeMap);
    }

    public static String[] getMapAppArrays(Context context) {
        if (!isBaiduMapAvailable(context) && !isGaodeMapAvailable(context)) {
            return null;
        } else if (isBaiduMapAvailable(context) && isGaodeMapAvailable(context)) {
            return new String[]{"百度地图", "高德地图"};
        } else if (isBaiduMapAvailable(context)) {
            return new String[]{"百度地图"};
        } else {
            return new String[]{"高德地图"};
        }
    }

    public static void gotoApp(Context context, String packageName) {
        if (isAvailable(context, packageName)) {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        } else {
            ToastUtils.showShort(context, "没有找到相关APP");
        }
    }

    /**
     * 启动高德App进行导航
     * <p>
     * //     * @param sourceApplication 必填 第三方调用应用名称。如 amap
     * <p>
     * //     * @param poiname 非必填 目的地名称
     *
     * @param lat 必填 终点纬度
     * @param lon 必填 终点经度
     *            //     * @param dev               必填 是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
     *            //     * @param style             必填 预设的导航方式 t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
     */
    public static void goToGaodeNaviActivity(Context context, double lat, double lon, String dName) {
        //启动路径规划页面
        String uri = "amapuri://route/plan/?dlat=" + lat + "&dlon=" + lon + "&dname=" + dName + "&dev=1&t=0";
        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(uri));
        intent.setPackage("com.autonavi.minimap");
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 启动百度App进行导航
     *
     * @param address 目的地
     * @param lat     必填 纬度
     * @param lon     必填 经度
     */
    public static void goToBaiduNaviActivity(Context context, String address, double lat, double lon) {
        double[] doubles = GPSUtil.gcj02_To_Bd09(lat, lon);
        //启动路径规划页面
        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("baidumap://map/direction?origin=" + doubles[0] + "," + doubles[1] + "&destination=" + address + "&mode=driving"));
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static String getAndroidId() {
        return Settings.System.getString(MyApplication.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);
    }

}
